package top.hidoctor.auscultation.feature.activity;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.content.DialogInterface;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.RequiresApi;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.flyco.tablayout.SegmentTabLayout;
import com.flyco.tablayout.listener.OnTabSelectListener;
import com.google.gson.reflect.TypeToken;
import com.tang.util.AppUtil;
import com.tang.util.DensityUtil;
import com.tang.util.DialogUtil;
import com.tang.util.GsonUtil;
import com.tang.util.SPUtil;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import top.hidoctor.auscultation.R;
import top.hidoctor.auscultation.adapter.ChooseAdapter2;
import top.hidoctor.auscultation.adapter.FileAdapter;
import top.hidoctor.auscultation.base.BaseActivity;
import top.hidoctor.auscultation.base.Constant;
import top.hidoctor.auscultation.bean.BlueFileBean;
import top.hidoctor.auscultation.bean.DictionaryBean;
import top.hidoctor.auscultation.bean.FileBean;
import top.hidoctor.auscultation.bean.PatientLocalInfo;
import top.hidoctor.auscultation.net.c.GatherContract;
import top.hidoctor.auscultation.net.p.GatherPresenter;
import top.hidoctor.auscultation.net.req.DictionaryReq;
import top.hidoctor.auscultation.utils.BlueToothDataUtils;
import top.hidoctor.auscultation.utils.BlueToothUtils;
import top.hidoctor.auscultation.utils.HexUtil;
import top.hidoctor.auscultation.utils.MyInternalStorage;

import static top.hidoctor.auscultation.feature.activity.DeviceActivity.BLUETOOTH_DEVICE;
import static top.hidoctor.auscultation.utils.BlueToothUtils.getBlueToothUtils;

public class FileDownActivity extends BaseActivity implements View.OnClickListener, GatherContract.View {
    private static final int OBTAIN_SUC = 1000;
    private static final int FILE_DOWN_SUC = 2000;
    private static final int FILE_DOWN_FAIL = 3000;
    private TextView tvNumber, tvStatus, tvTitle, tiwei, changsuo, peihe;
    private View viewStatus;
    private BlueToothUtils blueToothUtils;
    private BluetoothGatt bluetoothGatt;
    private String order = "";
    private RecyclerView rcFile;
    private FileAdapter fileAdapter;
    private List<FileBean> fileList = new ArrayList<>();
    private String cmdType = "";
    private List<String> pcmList = new ArrayList<>();
    private int pos = -1;
    private AlertDialog dialog;
    private EditText shengao, tizhong, address;
    private SegmentTabLayout tabZhenjing, tabShoushu;
    private String tiweiName, tiweiId, peiheName, peiheId, changsuoName, changsuoId, zhengjing = "0", shoushu = "0";
    private List<DictionaryBean.ResultBean> positionList = new ArrayList<>();
    private List<DictionaryBean.ResultBean> coordinateList = new ArrayList<>();
    private List<DictionaryBean.ResultBean> siteList = new ArrayList<>();
    private AlertDialog chooseDialog;
    private ChooseAdapter2 chooseAdapter;
    private GatherPresenter presenter;
    private DictionaryReq req;
    private String processedData;
    private MyInternalStorage myInternal;
    private String fileName = "";
    private List<PatientLocalInfo> list = new ArrayList<>();
    private MediaPlayer mediaPlayer;
    private boolean isDownload = false;//是否正在下载中

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_file_down);
        initView();
        initEvent();
    }


    private void initView() {
        Toolbar toolbar = findViewById(R.id.toolbar);
        toolbar.setNavigationIcon(R.mipmap.ic_back_left);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @SuppressLint("NewApi")
            @Override
            public void onClick(View v) {
                if (isDownload) {
                    stopDownload();
                } else {
                    if (TextUtils.isEmpty(cmdType) || cmdType.equals("b4")) {
                        finish();
                    } else {
                        order = "B400B400";//获取文件夹
                        cmdType = "b4";
                        tvTitle.setText("设备文件列表");
                        blueToothUtils.write(order);
                    }
                }
            }
        });
        tvNumber = findViewById(R.id.tv_number);
        tvStatus = findViewById(R.id.tv_status);
        viewStatus = findViewById(R.id.view_status);
        tvTitle = findViewById(R.id.tv_title);
        rcFile = findViewById(R.id.rc_file);
        rcFile.setLayoutManager(new LinearLayoutManager(this));
        rcFile.setAdapter(fileAdapter = new FileAdapter(R.layout.item_file, null));
        View view = LayoutInflater.from(this).inflate(R.layout.layout_empty_list, (ViewGroup) rcFile.getParent(), false);
        fileAdapter.setEmptyView(view);
        tvTitle.setText("设备文件列表");
        fileAdapter.setOnRecyclerViewItemClickListener(new BaseQuickAdapter.OnRecyclerViewItemClickListener() {
            @SuppressLint("NewApi")
            @Override
            public void onItemClick(View view, int position) {
                pos = position;
                if (cmdType.equals("b4")) {
                    tvTitle.setText(fileAdapter.getData().get(position).getTitle());
                    cmdType = "b5";
                    String b5 = BlueToothDataUtils.handleClickToTranslate(fileAdapter.getData().get(position).getTitle(), cmdType);
                    if (!TextUtils.isEmpty(b5)) {
                        order = b5;//获取文件夹中的文件
                        blueToothUtils.write(order);
                    }
                } else if (cmdType.equals("b5") || cmdType.equals("b6")) {//下载
                    String content = (String) SPUtil.get(FileDownActivity.this, Constant.LOCAL_INFO, "");
                    List<PatientLocalInfo> data = GsonUtil.parseJson(content, new TypeToken<List<PatientLocalInfo>>() {
                    });
                    cmdType = "b6";
                    if (fileAdapter.getData().get(position).isDownload()) {
                        if (data.size() > 0)
                            for (int i = 0; i < data.size(); i++) {
                                if (data.get(i).getName().contains(fileAdapter.getData().get(position).getTitle().split(".WAV")[0])) {
                                    startActivity(new Intent(FileDownActivity.this, XinyinDetailActivity.class)
                                            .putExtra("info", data.get(i)));
                                    break;
                                }
                            }
                    } else {
                        String b6 = BlueToothDataUtils.handleClickToTranslate(tvTitle.getText().toString() + "/" + fileAdapter.getData().get(position).getTitle(), cmdType);
                        if (!TextUtils.isEmpty(b6)) {
                            order = b6;//获取文件夹中的文件
                            blueToothUtils.write(order);
                            fileName = tvTitle.getText().toString() + "/" + fileAdapter.getData().get(position).getTitle();
                            showProgressDialog("下载中");
                            isDownload = true;
                        }
                    }
                }
            }
        });
        initDialog();
    }


    @SuppressLint("NewApi")
    private void initEvent() {
        //网络请求
        presenter = new GatherPresenter(this, this);
        req = new DictionaryReq();
        req.setGroupCode("SAMPLE_POSITION");
        presenter.getDictionary(req);
        req.setGroupCode("SAMPLE_COORDINATE");
        presenter.getDictionary(req);
        req.setGroupCode("SAMPLE_SITE");
        presenter.getDictionary(req);

        myInternal = new MyInternalStorage(this);


        //获取 本地数组文件
        String content = (String) SPUtil.get(this, Constant.LOCAL_INFO, "");
        if (!TextUtils.isEmpty(content)) {
            list = GsonUtil.parseJson(content, new TypeToken<List<PatientLocalInfo>>() {
            });
        }

        BluetoothDevice device = getIntent().getParcelableExtra(BLUETOOTH_DEVICE);
        if (device != null) {
            tvNumber.setText(device.getAddress());
            tvStatus.setText("在线");
            viewStatus.setBackground(getResources().getDrawable(R.drawable.green_point));
        } else {
            tvStatus.setText("离线");
            viewStatus.setBackground(getResources().getDrawable(R.drawable.red_point));
        }
        blueToothUtils = getBlueToothUtils();
        blueToothUtils.setSetMtu(true);
        bluetoothGatt = blueToothUtils.connect(device, this);
        blueToothUtils.setBlueToothHandle(new BlueToothUtils.BlueToothHandle() {
            @Override
            public void getCharacteristicChanged(byte[] data) {
                //  这里将蓝牙传过来的数据转换为 16 进制格式的字符串

                if (HexUtil.encodeHexStr(data).equals("ad0000ad00")) {//停止接受

                }
                if (data.length > 0) {
                    List<String> list = new ArrayList<>();
                    for (int i = 0; i < HexUtil.encodeHexStr(data).length() - 1; i += 2) {
                        list.add(HexUtil.encodeHexStr(data).substring(i, i + 2));
                    }
                    BlueFileBean blueFileBean = BlueToothDataUtils.dataRestructure(list);
                    if (blueFileBean != null) {
                        if (cmdType.equals("b4") || cmdType.equals("b5")) {
                            List<String> folderData = BlueToothDataUtils.getFolderData(blueFileBean.getData());
                            fileList.clear();
                            if (cmdType.equals("b4")) {
                                for (int i = 0; i < folderData.size(); i++) {
                                    fileList.add(new FileBean(folderData.get(i), cmdType, false));
                                }
                            } else {
                                String content = (String) SPUtil.get(FileDownActivity.this, Constant.LOCAL_INFO, "");
                                for (int i = 0; i < folderData.size(); i++) {
                                    boolean contains = TextUtils.isEmpty(content) ? false : content.contains(tvTitle.getText() + "/" + folderData.get(i).split(".WAV")[0]);
                                    fileList.add(new FileBean(folderData.get(i), cmdType, contains));
                                }
                            }
                            mHandler.sendEmptyMessage(OBTAIN_SUC);
                        } else if (cmdType.equals("b6")) {
                            pcmList.addAll(blueFileBean.getData());
                            if (blueFileBean.getEndSign().equals("00")) {
                                if (pcmList.size() > 100) {
                                    mHandler.sendEmptyMessage(FILE_DOWN_SUC);
                                } else {
                                    mHandler.sendEmptyMessage(FILE_DOWN_FAIL);
                                }
                            }
                        }
                    }
                }
                Log.i("TAG", "原数据： " + HexUtil.encodeHexStr(data));
            }

            @Override
            public void stateDisconnected() {
            }

            @Override
            public void stateDisconnecting() {

            }

            @Override
            public void stateConnected() {

            }

            @Override
            public void stateConnecting() {

            }

            @Override
            public void characteristicWrite(int status) {
//                if (status == BluetoothGatt.GATT_SUCCESS) {
//                    mHandler.sendEmptyMessage(WRITE_SUC);
//                } else {
//                    mHandler.sendEmptyMessage(WRITE_FAIL);
//                }
            }

            @Override
            public void startWrite() {
                //    获取列表一级
                Log.e("TAG", "startWrite: ");
                order = "B400B400";//获取文件夹
                cmdType = "b4";
                blueToothUtils.write(order);
            }
        });
    }


    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case OBTAIN_SUC://数据返回成功
                    fileAdapter.setNewData(fileList);
                    break;
                case FILE_DOWN_SUC://数据传输完成
                    showToast("下载完成");
                    fileAdapter.setNewData(fileList);
                    hideDialog();
                    disposeData();
                    isDownload = false;
                    break;
                case FILE_DOWN_FAIL://数据传输完成
                    showToast("数据已损坏");
                    hideDialog();
                    isDownload = false;
                    break;
            }
        }
    };

    /**
     * 暂存数据
     */
    private void disposeData() {
        if (pcmList.size() == 0) {
            return;
        }
        try {
            // pcm 文件过度缓存
            processedData = pcmList.toString().replace(",", "").replace(" ", "");
            myInternal.save("temporary_content.pcm", processedData.substring(1, processedData.length() - 1));
            pcmList.clear();
            dialog.show();
        } catch (Exception e) {
            showToast("保存失敗,请重试");
            pcmList.clear();
            //关闭保存弹窗
//            dialog.dismiss();
            e.printStackTrace();
        }
    }


    /**
     * 初始化弹窗
     */
    private void initDialog() {
        String[] choose = {"否", "是"};
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        final View dialogView = LayoutInflater.from(this).inflate(R.layout.dialog_save_content, null);
        builder.setView(dialogView);
        dialog = builder.create();
        dialog.setCanceledOnTouchOutside(false);

        TextView tvCancel = dialogView.findViewById(R.id.tv_cancel);
        TextView tvSave = dialogView.findViewById(R.id.tv_save);
        shengao = dialogView.findViewById(R.id.edit_shengao);
        tizhong = dialogView.findViewById(R.id.edit_tizhong);
        address = dialogView.findViewById(R.id.edit_address);
        tiwei = dialogView.findViewById(R.id.tv_tiwei);
        peihe = dialogView.findViewById(R.id.tv_peihe);
        changsuo = dialogView.findViewById(R.id.tv_changsuo);
        tabZhenjing = dialogView.findViewById(R.id.tab_zhenjing);
        tabShoushu = dialogView.findViewById(R.id.tab_shoushu);
        tabZhenjing.setTabData(choose);
        tabShoushu.setTabData(choose);
        tabZhenjing.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelect(int position) {
                zhengjing = position + "";
            }

            @Override
            public void onTabReselect(int position) {

            }
        });
        tabShoushu.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelect(int position) {
                shoushu = position + "";
            }

            @Override
            public void onTabReselect(int position) {

            }
        });

        tiwei.setOnClickListener(this);
        peihe.setOnClickListener(this);
        changsuo.setOnClickListener(this);
        tvSave.setOnClickListener(this);
        tvCancel.setOnClickListener(this);

    }


    @SuppressLint("NewApi")
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_tiwei:
                if (!AppUtil.isFastClick()) {
                    hideSoft(tiwei);
                    showPick(1);
                }
                break;
            case R.id.tv_peihe:
                if (!AppUtil.isFastClick()) {
                    hideSoft(peihe);
                    showPick(2);
                }
                break;
            case R.id.tv_changsuo:
                if (!AppUtil.isFastClick()) {
                    hideSoft(changsuo);
                    showPick(3);
                }
                break;
            case R.id.tv_save:

                //
                String shengao = this.shengao.getText().toString();
                String tizhong = this.tizhong.getText().toString();
                String tiwei = this.tiwei.getText().toString();
                String peihe = this.peihe.getText().toString();
                String changsuo = this.changsuo.getText().toString();
                String address = this.address.getText().toString();
                if (TextUtils.isEmpty(shengao)) {
                    showToast("请输入身高");
                    return;
                }
                if (TextUtils.isEmpty(tizhong)) {
                    showToast("请输入体重");
                    return;
                }
                if (TextUtils.isEmpty(tiwei)) {
                    showToast("请选择体位");
                    return;
                }
                if (TextUtils.isEmpty(peihe)) {
                    showToast("请选择配合程度");
                    return;
                }
                if (TextUtils.isEmpty(changsuo)) {
                    showToast("请选择采集场所");
                    return;
                }
                //保存文件到本地
                try {
                    String data = myInternal.get("temporary_content.pcm");
                    if (TextUtils.isEmpty(data)) {
                        showToast("保存失败，请重试");
                        return;
                    }
                    //pcm 转 wav
                    final String path = getFilesDir().getAbsolutePath() + "/temporary_content.pcm";
                    long time = System.currentTimeMillis();
                    final String outpath = path.replace("temporary_content.pcm", "循音科技-" + time + ".wav");

                    BlueToothDataUtils.convertPCMFileToWAVFile(8000, (short) 1, (short) 16, outpath, HexUtil.hexStringToBytes(data));
                    if (processedData != null) {
                        myInternal.save("循音科技-" + time + ".pcm", data);
                    }
                    list.add(new PatientLocalInfo(
                            shengao, tizhong, tiweiName, tiweiId, peiheName, peiheId,
                            zhengjing, shoushu, changsuoName, changsuoId, address,
                            "循音科技-" + time + ".wav", "循音科技-" + time + ".pcm", time, 2, BlueToothDataUtils.getDuration(outpath), fileName.split(".WAV")[0]));
                    SPUtil.put(FileDownActivity.this, Constant.LOCAL_INFO, GsonUtil.toJsonStr(list));
                    showToast("保存成功");
                    if (pos != -1) {
                        fileList.get(pos).setDownload(true);
                        fileAdapter.notifyItemChanged(pos);
                    }
                    dialog.dismiss();
                    //初始化
                    this.shengao.setText("");
                    this.tizhong.setText("");
                    this.address.setText("");
                    for (DictionaryBean.ResultBean bean : positionList) {
                        bean.setCheck(false);
                    }
                    for (DictionaryBean.ResultBean bean : coordinateList) {
                        bean.setCheck(false);
                    }
                    for (DictionaryBean.ResultBean bean : siteList) {
                        bean.setCheck(false);
                    }

                    tabShoushu.setCurrentTab(0);
                    tabZhenjing.setCurrentTab(0);
                    this.tiwei.setText("");
                    this.peihe.setText("");
                    this.changsuo.setText("");

                } catch (IOException e) {
                    e.printStackTrace();
                }
                break;
            case R.id.tv_cancel:
                dialog.dismiss();
                break;
        }
    }


    /**
     * 选择体位 配合程度  采集场所
     *
     * @param type
     */
    private void showPick(final int type) {
        final List<String> list = new ArrayList<>();
        if (type == 1) {
            for (int i = 0; i < positionList.size(); i++) {
                list.add(positionList.get(i).getTitle());
            }
        } else if (type == 2) {
            for (int i = 0; i < coordinateList.size(); i++) {
                list.add(coordinateList.get(i).getTitle());
            }
        } else if (type == 3) {
            for (int i = 0; i < siteList.size(); i++) {
                list.add(siteList.get(i).getTitle());
            }
        }

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        final View dialogView = LayoutInflater.from(this).inflate(R.layout.dialog_choose, null);
        builder.setView(dialogView);
        chooseDialog = builder.create();
        chooseDialog.setCanceledOnTouchOutside(true);
        chooseDialog.show();
        chooseDialog.getWindow().setLayout(DensityUtil.dip2px(this, 240), DensityUtil.dip2px(this, 300));
        RecyclerView rc = dialogView.findViewById(R.id.rc);
        TextView tvTitle = dialogView.findViewById(R.id.tv_title);
        rc.setLayoutManager(new LinearLayoutManager(this));
        rc.setAdapter(chooseAdapter = new ChooseAdapter2(R.layout.item_choose, null));
        if (type == 1) {
            chooseAdapter.setNewData(positionList);
            tvTitle.setText("请选择：体位");
        } else if (type == 2) {
            chooseAdapter.setNewData(coordinateList);
            tvTitle.setText("请选择：配合程度");
        } else if (type == 3) {
            chooseAdapter.setNewData(siteList);
            tvTitle.setText("请选择：采集场所");
        }
        chooseAdapter.setOnRecyclerViewItemClickListener(new BaseQuickAdapter.OnRecyclerViewItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                if (type == 1) {
                    for (int i = 0; i < positionList.size(); i++) {
                        positionList.get(i).setCheck(false);
                    }
                    positionList.get(position).setCheck(true);
                    tiwei.setText(positionList.get(position).getTitle());
                    tiweiName = positionList.get(position).getTitle();
                    tiweiId = positionList.get(position).getId();
                } else if (type == 2) {
                    for (int i = 0; i < coordinateList.size(); i++) {
                        coordinateList.get(i).setCheck(false);
                    }
                    coordinateList.get(position).setCheck(true);
                    peihe.setText(coordinateList.get(position).getTitle());
                    peiheName = coordinateList.get(position).getTitle();
                    peiheId = coordinateList.get(position).getId();
                } else if (type == 3) {
                    for (int i = 0; i < siteList.size(); i++) {
                        siteList.get(i).setCheck(false);
                    }
                    siteList.get(position).setCheck(true);
                    changsuo.setText(siteList.get(position).getTitle());
                    changsuoName = siteList.get(position).getTitle();
                    changsuoId = siteList.get(position).getId();
                }
                chooseAdapter.notifyDataSetChanged();
                chooseDialog.dismiss();
            }
        });
    }


    @Override
    public void getDictionarySuc(DictionaryBean bean) {
        String groupCode = "";
        if (bean.getResult().size() > 0) {
            groupCode = bean.getResult().get(0).getGroupCode();
        }
        if (groupCode.equals("SAMPLE_POSITION")) {
            positionList.addAll(bean.getResult());
        } else if (groupCode.equals("SAMPLE_COORDINATE")) {
            coordinateList.addAll(bean.getResult());
        } else if (groupCode.equals("SAMPLE_SITE")) {
            siteList.addAll(bean.getResult());
        }
    }


    @SuppressLint("NewApi")
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (bluetoothGatt != null) {
            bluetoothGatt.disconnect();
        }
        if (mediaPlayer != null) {
            mediaPlayer.stop();
            mediaPlayer = null;
        }
    }

    @SuppressLint("NewApi")
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            if (isDownload) {
                stopDownload();
            } else {
                if (TextUtils.isEmpty(cmdType) || cmdType.equals("b4")) {
                    finish();
                } else {
                    order = "B400B400";//获取文件夹
                    cmdType = "b4";
                    tvTitle.setText("设备文件列表");
                    blueToothUtils.write(order);
                }
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 终止下载
     */
    private void stopDownload() {
        showAlertDialog("", "确定停止下载吗?", new DialogUtil.DialogButtonClickListener() {
            @SuppressLint("NewApi")
            @Override
            public void onPositiveButtonClick(DialogInterface dialog) {
                String b6 = BlueToothDataUtils.handleClickToTranslate("0", "b6");
                if (!TextUtils.isEmpty(b6)) {
                    order = b6;//获取文件夹中的文件
                    blueToothUtils.write(order);
                    isDownload = false;
                }
            }

            @Override
            public void onNegativeButtonClick(DialogInterface dialog) {
                dialog.dismiss();
            }
        });
    }


}
